// JavaScript Document
// Show a custom alert
//
function normalAlertDismissCB(){
	//do nothing...
}
function showAlert(message,alertDismissed,title,buttonName) {
	navigator.notification.alert(
		message,  // message
		alertDismissed,         // callback
		title,            // title
		buttonName                  // buttonName
	);
}


/***************************
* login function
****************************/
$('#loginForm').live("submit",function (event){
	//event.preventDefault();
	
	//form validation
	var emailVar = $('#loginForm #email').val();
	var passwordVar = $('#loginForm #password').val();
	
	
	if(emailVar=="" || passwordVar==""){
		//missing 
		event.preventDefault();
		showAlert('Please fill all fields',normalAlertDismissCB,'Naughty!','OK');
		return false;
	}
	
	if(!isValidEmail(emailVar)){
		event.preventDefault();
		showAlert('Email not valid',normalAlertDismissCB,'Sorry!','OK');
		return false;	
	}
	
	var postData = $(this).serialize();
	var remember = $('#loginForm #remember').is(':checked');
	$.ajax({
		type: 'POST',
		data: postData,
		url: 'http://seanwuapps.com/Partiest/user/login.php',
		success: function(data){
			if(data.indexOf("Error") != (-1)){
				//error			
				showAlert(data,normalAlertDismissCB,'Oops!','OK');
			}else{
				if(remember){
					//set local storage key value
					window.localStorage.setItem("remember", "true");
				}else{
					//clear local storage
					window.localStorage.removeItem("remember");
				}
				
				//load main menu page
				$.mobile.changePage($("#main_menu"));
			}
		},
		error: function(x,t,m){
			if(t==='timeout'){
				alert('timed out');
			}else{
				alert('Something terrible just happend and need to be fixed');
			}
		}
	});
	
	return false;
});



/***************************
* register function
****************************/
$('#registerForm').live("submit",function (event){
	//event.preventDefault();
	
	//form validation
	var emailVar = $('#registerForm #email').val();
	var passwordVar = $('#registerForm #password').val();
	var confirmVar =  $('#registerForm #confirm').val();
	var agreed = $('#registerForm #agree').is(':checked');
	
	if(emailVar=="" || passwordVar=="" || confirmVar==""){
		//formvalidation failed
		event.preventDefault();
		showAlert('Please fill in all fields to register',normalAlertDismissCB,'Sorry!','OK');
		return false;
	}
	if(!isValidEmail(emailVar)){
		event.preventDefault();
		showAlert('Email not valid',normalAlertDismissCB,'Sorry!','OK');
		return false;	
	}
	if(passwordVar != confirmVar){
		//formvalidation failed
		event.preventDefault();
		showAlert('Password confirmation not same',normalAlertDismissCB,'Sorry!','OK');
		return false;
	}
	if(!agreed){
		//formvalidation failed
		event.preventDefault();
		showAlert('You need to agree the terms and conditions to register',normalAlertDismissCB,'Sorry!','OK');
		return false;
	}
	
	var postData = $(this).serialize();
	$.ajax({
		type: 'POST',
		data: postData,
		url: 'http://seanwuapps.com/Partiest/user/register.php',
		success: function(data){
			if(data.indexOf("Error") != (-1)){
				//error			
				showAlert(data,normalAlertDismissCB,'Oops!','OK');
			}else{
				//load main menu page
				$.mobile.changePage($("#main_menu"));
			}
		},
		error: function(x,t,m){
			if(t==='timeout'){
				alert('timed out');
			}else{
				alert('Something terrible just happend and need to be fixed');
			}
		}
	});
	
	return false;
});

/***************************
* forgot passwords function
****************************/
$('#forgotPasswordForm').live("submit",function (event){
	//event.preventDefault();
	
	//form validation
	var emailVar = $('#forgotPasswordForm #email').val();
	
	if(emailVar==""){
		//formvalidation failed
		event.preventDefault();
		showAlert('We need your email address to start your password reset process',normalAlertDismissCB,'Sorry!','OK');
		return false;
	}
	if(!isValidEmail(emailVar)){
		event.preventDefault();
		showAlert('Email not valid',normalAlertDismissCB,'Sorry!','OK');
		return false;	
	}
	
	var postData = $(this).serialize();
	$.ajax({
		type: 'POST',
		data: postData,
		url: 'http://seanwuapps.com/Partiest/user/reset_password.php',
		success: function(data){
			if(data.indexOf("Error") != (-1)){
				//error			
				showAlert(data,normalAlertDismissCB,'Oops!','OK');
			}else{
				//load main menu page
				showAlert(data,normalAlertDismissCB(),"Email sent", 'OK');
			}
		},
		error: function(x,t,m){
			if(t==='timeout'){
				alert('timed out');
			}else{
				alert('Something terrible just happend and need to be fixed');
			}
		}
	});
	
	return false;
});




function isValidEmail(email){
	var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	return filter.test(email);
}




/*********************************
 * facebook connection
*********************************/
if ((typeof cordova == 'undefined') && (typeof Cordova == 'undefined')) alert('Cordova variable does not exist. Check that you have included cordova.js correctly');
if (typeof CDV == 'undefined') alert('CDV variable does not exist. Check that you have included cdv-plugin-fb-connect.js correctly');
if (typeof FB == 'undefined') alert('FB variable does not exist. Check that you have included the Facebook JS SDK file.');

FB.Event.subscribe('auth.login', function(response) {
                   alert('auth.login event');
                   });

FB.Event.subscribe('auth.logout', function(response) {
                   alert('auth.logout event');
                   });

FB.Event.subscribe('auth.sessionChange', function(response) {
                   alert('auth.sessionChange event');
                   });

FB.Event.subscribe('auth.statusChange', function(response) {
                   alert('auth.statusChange event');
                   });

/*function getSession() {
    alert("session: " + JSON.stringify(FB.getSession()));
}
*/
function fb_redirect_user() {
    FB.getLoginStatus(function(response) {
                      if (response.status == 'connected') {
                    	  window.location="index.html#main_menu";
                      } else {
                    	  return false;
                      }
                      });
}
var friendIDs = [];
var fdata;
function me() {
    FB.api('/me/friends', { fields: 'id, name, picture' },  function(response) {
           if (response.error) {
           alert(JSON.stringify(response.error));
           } else {
           var data = document.getElementById('data');
		   fdata=response.data;
		   console.log("fdata: "+fdata);
           response.data.forEach(function(item) {
                                 var d = document.createElement('div');
                                 d.innerHTML = "<img src="+item.picture+"/>"+item.name;
                                 data.appendChild(d);
                                 });
           }
		var friends = response.data;
		console.log(friends.length); 
		for (var k = 0; k < friends.length && k < 200; k++) {
	        var friend = friends[k];
	        var index = 1;

	        friendIDs[k] = friend.id;
	        //friendsInfo[k] = friend;
		}
		console.log("friendId's: "+friendIDs);
           });
}

function logout() {
    FB.logout(function(response) {
              alert('logged out');
              });
}

function login() {
    FB.login(
             function(response) {
            	 //alert('response from login event: '+JSON.stringify(response));
            	 
	             if (response.status=='connected') {
	            	 alert('logged in');
	            	 /*
	            	  * create user in Partiest database
	            	  */
	            	 //grab user information
	            	 var picture_url = '';
	            	 FB.api('/me', function(response) {
	            		 alert(JSON.stringify(response));
	            		 alert(response.name);
	            		 alert(response.email);
	            		 picture_url = 'http://graph.facebook.com/'+response.username+'/picture';
	            		 $('#profile_picture').html('<img src="'+picture_url+'" alt="profile image"></img>');
	            	 });
	            	 //add record into database using AJAX call
	            	 //create this function: create_partiest_user(email,first_name,last_name,picture_url);
	            	 
	            	 //fb_redirect_user();
	            	 
	             } else {
	            	 alert('not logged in');
	             }
             },
             	{ scope: "email" }
             );
}


function facebookWallPost() {
    console.log('Debug 1');
	var params = {
	    method: 'feed',
	    name: 'Facebook Dialogs',
	    link: 'https://developers.facebook.com/docs/reference/dialogs/',
	    picture: 'http://fbrell.com/f8.jpg',
	    caption: 'Reference Documentation',
	    description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
	  };
	console.log(params);
    FB.ui(params, function(obj) { console.log(obj);});
}

function publishStoryFriend() {
	randNum = Math.floor ( Math.random() * friendIDs.length ); 

	var friendID = friendIDs[randNum];
	if (friendID == undefined){
		alert('please click the me button to get a list of friends first');
	}else{
    	console.log("friend id: " + friendID );
        console.log('Opening a dialog for friendID: ', friendID);
        var params = {
        	method: 'feed',
            to: friendID.toString(),
            name: 'Facebook Dialogs',
            link: 'https://developers.facebook.com/docs/reference/dialogs/',
            picture: 'http://fbrell.com/f8.jpg',
            caption: 'Reference Documentation',
            description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
     	};
		FB.ui(params, function(obj) { console.log(obj);});
    }
}

document.addEventListener('deviceready', function() {
                          try {
                          FB.init({ appId: "287591978011452", nativeInterface: CDV.FB, useCachedDialogs: false });
                          //document.getElementById('data').innerHTML = "";
                          //fb_redirect_user();
                          } catch (e) {
                          alert(e);
                          }
                          }, false);


